﻿using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using oAuth;
using Twitterizer;
using System.Threading;
using System.Windows.Threading;
using System.Linq;
using Twitterizer.Entities;
namespace Twicko {


    /// <summary>
    /// Interaction logic for Window1.xaml
    /// </summary>
    public partial class ApplicationWindow : Window {
        oAuthTwitter oAuth;
        int m_period = 5000;
        private DispatcherTimer timer;
        private TimelineOptions options = new TimelineOptions();

        public ApplicationWindow(oAuthTwitter oAuth) {
            InitializeComponent();

            this.oAuth = oAuth;
            this.options.SinceStatusId = -1;
            
            timer = new DispatcherTimer();
            timer.Interval = TimeSpan.FromMilliseconds(30000);
            timer.Tick += new EventHandler(OnTimer);
            timer.Start();
            geraPosts();
        }

        void TimerThread() {
            Thread.Sleep(m_period);
            Console.WriteLine("Chamou");
//            OnTimer();
        }

        void OnTimer(object sender, EventArgs e) {
            //Console.WriteLine("Chamou");
            geraPosts();
        }

        private void geraPosts() {
            OAuthTokens tokens = new OAuthTokens();
            tokens.AccessToken = oAuth.Token;
            tokens.AccessTokenSecret = oAuth.TokenSecret;
            tokens.ConsumerKey = oAuth.ConsumerKey;
            tokens.ConsumerSecret = oAuth.ConsumerSecret;

            TwitterResponse<TwitterStatusCollection> showUserResponse = TwitterTimeline.HomeTimeline(tokens, options);
            if (showUserResponse.Result == RequestResult.Success) {
                foreach (TwitterStatus cStatus in showUserResponse.ResponseObject.OrderBy(x => x.Id)) {
                    UserStatus us = new UserStatus(cStatus.User.ProfileImageLocation, cStatus.User.ScreenName, cStatus.User.Name, cStatus.Text);
                    this.stackPanel.Children.Insert(this.stackPanel.Children.Capacity - this.stackPanel.Children.Count, us);
                    

                    if (cStatus.Id > this.options.SinceStatusId) {
                        this.options.SinceStatusId = cStatus.Id;
                    }
                }

            } else {
                //DisplayError(showUserResponse.ErrorMessage);
            }



        }
    }
}
